import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2022-10-29
 * Time: 19:54
 */
//查找文件
public class TestDemo1 {
    public static void main(String[] args) {
        Scanner scanner =new Scanner(System.in);
        System.out.println("请输入要扫描的路径");
        String rootDirPath=scanner.next();
        System.out.println("请输入要删除的文件名");
        String fileName=scanner.next();
        File file=new File(rootDirPath);
        if(!file.isDirectory()){
            System.out.println("输入的扫描路径有误");
            return;
        }
        try {
            scan(file,fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //开始查找,类似于二叉树的dfs
    public static void scan(File file,String fileName) throws IOException {
        //先列出该目录中都有那些文件
        File[] files=file.listFiles();
        //如果是空目录直接返回
        if(files==null){
            return;
        }
        //开始遍历文件
        for (File file2: files) {
            //如果是文件判断是否该删除
            if(file2.isFile()){
                String name=file2.getName();
                //包含了这个文件名就删除
                if(name.contains(fileName)){
                    delete(file2);
                }
            }else{//如果是目录(文件夹)递归
                scan(file2,fileName);
            }
        }

    }
    public static void delete(File file) throws IOException {
        System.out.println(file.getCanonicalFile());
        System.out.println("确定要删除该文件  Y/N");
        Scanner scanner=new Scanner(System.in);
        String str=scanner.next();
        if(str.equals("Y")){
            file.delete();
            System.out.println("删除成功");
        }else{
            System.out.println("删除已取消");
        }
    }
}
